<template>
  <div class="beefgate-container">
    <h1>聚合静态码收银台</h1>
    <div v-if="isBrowser" class="mb-4">
      <div class="flex items-center space-x-4">
        <label class="inline-flex items-center">
          <input
            type="checkbox"
            v-model="useMockData"
            class="form-checkbox h-5 w-5 text-blue-600"
          >
          <span class="ml-2">使用模拟数据</span>
        </label>
        <div class="flex items-center space-x-2">
          <span>模拟环境：</span>
          <a-select
            v-model:value="mockEnvironment"
            style="width: 120px"
            @change="handleEnvironmentChange"
          >
            <a-select-option value="Browser">浏览器</a-select-option>
            <a-select-option value="WeChat">微信</a-select-option>
            <a-select-option value="Alipay">支付宝</a-select-option>
            <a-select-option value="QQ">QQ</a-select-option>
          </a-select>
        </div>
      </div>
    </div>
    <div v-if="qrcode">
      <p>QRCode: {{ qrcode }}</p>
      <p>环境: {{ environment }}</p>
      <div v-if="loading" class="loading">正在加载二维码信息...</div>
      <div v-if="error" class="error">{{ error }}</div>
      <div v-if="qrCodeData" class="qr-data">
        <a-collapse>
          <a-collapse-panel key="1" header="二维码信息">
            <pre>{{ JSON.stringify(qrCodeData, null, 2) }}</pre>
          </a-collapse-panel>
        </a-collapse>
        <!-- 根据 qrCodeData.pageType 和 environment 渲染不同的支付引导 -->
        <div v-if="qrCodeData.pageType === 'WXPAY_H5' && environment === 'WeChat'">
          <p>请在微信中完成支付...</p>
          <!-- 实际项目中这里会调用微信JSAPI -->
        </div>
        <div v-else-if="qrCodeData.pageType === 'ALIPAY_H5' && environment === 'Alipay'">
          <p>请在支付宝中完成支付...</p>
          <div v-if="!authUrl" class="mt-4">
            <a-button type="primary" @click="handleGetAuthUrl" :loading="authLoading">
              获取授权
            </a-button>
          </div>
          <div v-else class="mt-4">
            <p>授权链接已生成，正在跳转...</p>
            <p class="text-sm text-gray-500">如果没有自动跳转，请<a :href="authUrl" class="text-blue-500">点击这里</a></p>
          </div>
        </div>
        <div v-else>
          <p>请使用{{ qrCodeData.pageType }}进行支付。</p>
        </div>
        <div v-if="authUrl" class="mt-4">
          <a-alert type="info" show-icon>
            <template #message>
              授权链接：<a :href="authUrl" target="_blank" class="text-blue-600 break-all">{{ authUrl }}</a>
            </template>
          </a-alert>
        </div>
        <div v-if="alipayAuthCode && (environment === 'Alipay' || (useMockData && mockEnvironment === 'Alipay'))" class="mt-4">
          <a-alert type="success" show-icon>
            <template #message>
              已完成支付宝授权，授权码：<span class="font-mono text-blue-600">{{ alipayAuthCode }}</span>
              <template v-if="alipayBuyerId">
                <br />支付宝 buyerId：<span class="font-mono text-green-600">{{ alipayBuyerId }}</span>
              </template>
            </template>
          </a-alert>
        </div>
        <div v-if="wechatAuthCode && (environment === 'WeChat' || (useMockData && mockEnvironment === 'WeChat'))" class="mt-4">
          <a-alert type="success" show-icon>
            <template #message>
              已完成微信授权，授权码：<span class="font-mono text-blue-600">{{ wechatAuthCode }}</span>
              <template v-if="wechatBuyerId">
                <br />微信 buyerId：<span class="font-mono text-green-600">{{ wechatBuyerId }}</span>
              </template>
            </template>
          </a-alert>
        </div>
      </div>
    </div>
    <div v-else>
      <p>无效的二维码参数。</p>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, watch, computed } from 'vue';
import { useRoute } from 'vue-router';
import axios from 'axios';

// 模拟后端返回的 QrcodeParams 结构
interface QrcodeParams {
  pageType: string; // 端内H5微信，端内H5支付宝，端内微信小程序，端内支付宝小程序，NORMAL_BROWSER_H5
  merchantId: string;
  merchantName: string;
  paymentMethods: string[];
  wechatAppId?: string;
  wechatMiniProgramOriginalId?: string;
  alipayAppId?: string;
  alipayMiniProgramId?: string;
  isNormalMerchantMode: boolean;
  paymentChannel: string;
  channelMerchantId: string;
  orderAmount?: number;
  productDescription?: string;
  attach?: string;
  notifyUrl: string;
  redirectUrl?: string;
  subAppId?: string;
  subMchId?: string;
  // ... 其他参数
}

export default defineComponent({
  name: 'BeefgatePage',
  setup() {
    const route = useRoute();
    const qrcode = ref<string | null>(null);
    const environment = ref<string>('Unknown');
    const mockEnvironment = ref<string>('Browser');
    const qrCodeData = ref<QrcodeParams | null>(null);
    const loading = ref<boolean>(false);
    const error = ref<string | null>(null);
    const useMockData = ref(true); // 控制是否使用模拟数据
    const authUrl = ref<string>('');
    const authLoading = ref<boolean>(false);
    const alipayAuthCode = ref<string | null>(null);
    const alipayBuyerId = ref<string | null>(null);
    const wechatAuthCode = ref<string | null>(null);
    const wechatBuyerId = ref<string | null>(null);

    // 判断是否在浏览器环境中
    const isBrowser = computed(() => {
      const ua = navigator.userAgent.toLowerCase();
      return !ua.includes('micromessenger') &&
             !ua.includes('alipayclient') &&
             !ua.includes('qq');
    });

    const detectEnvironment = () => {
      // 如果使用模拟环境，直接返回模拟的环境
      if (useMockData.value && isBrowser.value) {
        return mockEnvironment.value;
      }

      // 否则检测真实环境
      const ua = navigator.userAgent.toLowerCase();
      if (ua.includes('micromessenger')) {
        return 'WeChat';
      }
      if (ua.includes('alipayclient')) {
        return 'Alipay';
      }
      if (ua.includes('qq')) {
        return 'QQ';
      }
      return 'Browser';
    };

    const handleEnvironmentChange = (value: string) => {
      mockEnvironment.value = value;
      environment.value = value;
      // 如果切换到支付宝环境且有二维码数据，自动获取授权链接
      if (value === 'Alipay' && qrCodeData.value?.pageType === 'ALIPAY_H5' && !authUrl.value) {
        handleGetAuthUrl();
      }
    };

    const fetchQrCodeData = async (code: string) => {
      loading.value = true;
      error.value = null;
      console.log(`向后端请求二维码信息, qrcode: ${code}`);
      try {
        if (useMockData.value) {
          // 根据当前环境设置pageType
          let pageType = 'NORMAL_BROWSER_H5';
          if (environment.value === 'WeChat') {
            pageType = 'WXPAY_H5';
          } else if (environment.value === 'Alipay') {
            pageType = 'ALIPAY_H5';
          }

          // 使用模拟数据
          qrCodeData.value = {
            pageType,
            merchantId: '123456',
            merchantName: '测试商户',
            paymentMethods: ['WXPAY_PAY', 'ALIPAY'],
            wechatAppId: 'wx123456789',
            alipayAppId: '2021000000000000',
            isNormalMerchantMode: true,
            paymentChannel: 'WXPAY_DIRECT',
            channelMerchantId: '1234567890',
            orderAmount: 0.01,
            productDescription: '测试商品',
            notifyUrl: 'https://api.example.com/notify',
            redirectUrl: 'https://example.com/success'
          } as QrcodeParams;
        } else {
          // 使用实际 API 请求
          const response = await fetch(`/api/qrcode/entry?qrcode=${code}`);
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
          const data = await response.json();
          // 根据当前环境设置pageType
          let pageType = 'NORMAL_BROWSER_H5';
          if (environment.value === 'WeChat') {
            pageType = 'WXPAY_H5';
          } else if (environment.value === 'Alipay') {
            pageType = 'ALIPAY_H5';
          }
          qrCodeData.value = {
            ...data,
            pageType
          };
        }
      } catch (e: any) {
        console.error('获取二维码信息失败:', e);
        error.value = `获取二维码信息失败: ${e.message}`;
        qrCodeData.value = null;
      } finally {
        loading.value = false;
      }
    };

    const handleGetAuthUrl = async () => {
      if (!qrcode.value || !qrCodeData.value) {
        error.value = '二维码信息不完整';
        return;
      }

      authLoading.value = true;
      try {
        const redirectUri = window.location.href;
        // 根据当前环境设置正确的环境参数
        const env = environment.value.toLowerCase();
        const response = await axios.get(`/api/qrcode/entry/auth/url`, {
          params: {
            qrcode: qrcode.value,
            env: env,
            redirectUri
          }
        });

        if (response.data.code === 0 && response.data.data?.authUrl) {
          authUrl.value = response.data.data.authUrl;
          // 自动跳转到授权页面
          window.location.href = authUrl.value;
        } else {
          throw new Error(response.data.message || '获取授权链接失败');
        }
      } catch (e: any) {
        console.error('获取授权链接失败:', e);
        error.value = `获取授权链接失败: ${e.message}`;
      } finally {
        authLoading.value = false;
      }
    };

    // 获取buyerId
    const fetchAlipayBuyerId = async (authCode: string) => {
      try {
        const response = await axios.get('/api/qrcode/entry/alipay/buyerid', {
          params: {
            auth_code: authCode,
            qrcode: qrcode.value
          }
        });
        if (response.data.code === 0 && response.data.data?.buyerId) {
          alipayBuyerId.value = response.data.data.buyerId;
        } else {
          alipayBuyerId.value = null;
          error.value = response.data.message || '获取buyerId失败';
        }
      } catch (e: any) {
        alipayBuyerId.value = null;
        error.value = `获取buyerId失败: ${e.message}`;
      }
    };

    // 获取微信buyerId
    const fetchWechatBuyerId = async (code: string) => {
      try {
        const response = await axios.get('/api/qrcode/entry/wechat/buyerid', {
          params: {
            code: code,
            qrcode: qrcode.value
          }
        });
        if (response.data.code === 0 && response.data.data?.buyerId) {
          wechatBuyerId.value = response.data.data.buyerId;
        } else {
          wechatBuyerId.value = null;
          error.value = response.data.message || '获取buyerId失败';
        }
      } catch (e: any) {
        wechatBuyerId.value = null;
        error.value = `获取buyerId失败: ${e.message}`;
      }
    };

    // 处理支付宝授权流程
    const handleAlipayAuth = () => {
      if (isAlipayAuthCallback()) {
        // 如果已经有授权码，直接显示
        alipayAuthCode.value = (route.query.auth_code as string) || (route.query.code as string) || null;
        // 获取buyerId
        if (alipayAuthCode.value) {
          fetchAlipayBuyerId(alipayAuthCode.value);
        }
        return;
      }

      // 如果没有授权链接且是支付宝H5环境，获取授权链接并自动跳转
      if (!authUrl.value && qrCodeData.value?.pageType === 'ALIPAY_H5' && environment.value === 'Alipay') {
        handleGetAuthUrl();
      }
    };

    // 处理微信授权流程
    const handleWechatAuth = () => {
      if (isWechatAuthCallback()) {
        // 如果已经有授权码，直接显示
        wechatAuthCode.value = route.query.code as string || null;
        // 获取buyerId
        if (wechatAuthCode.value) {
          fetchWechatBuyerId(wechatAuthCode.value);
        }
        return;
      }

      // 如果没有授权链接且是微信H5环境，获取授权链接并自动跳转
      if (!authUrl.value && qrCodeData.value?.pageType === 'WXPAY_H5' && environment.value === 'WeChat') {
        handleGetAuthUrl();
      }
    };

    function isAlipayAuthCallback() {
      return !!(route.query.auth_code || route.query.code);
    }

    function isWechatAuthCallback() {
      return !!route.query.code;
    }

    // 监听环境变化，重新获取二维码数据
    watch([environment, useMockData], () => {
      if (qrcode.value) {
        fetchQrCodeData(qrcode.value);
      }
    });

    // 监听二维码数据变化，处理支付宝授权
    watch(qrCodeData, (newData) => {
      if (newData?.pageType === 'ALIPAY_H5' && environment.value === 'Alipay') {
        handleAlipayAuth();
      }
    });

    // 监听二维码数据变化，处理微信授权
    watch(qrCodeData, (newData) => {
      if (newData?.pageType === 'WXPAY_H5' && environment.value === 'WeChat') {
        handleWechatAuth();
      }
    });

    onMounted(() => {
      const qrParam = route.query.qrcode;
      if (typeof qrParam === 'string' && qrParam) {
        qrcode.value = qrParam;
        console.log('QRCode from URL:', qrcode.value);
      } else {
        console.error('未找到 qrcode 参数或参数无效');
        error.value = '无效的二维码参数。';
        return;
      }

      // 只在浏览器环境下允许使用模拟数据
      useMockData.value = isBrowser.value;

      environment.value = detectEnvironment();
      console.log('当前环境:', environment.value);

      if (qrcode.value) {
        fetchQrCodeData(qrcode.value);
      }

      // 检查是否是授权回调
      handleAlipayAuth();
      handleWechatAuth();
    });

    return {
      qrcode,
      environment,
      mockEnvironment,
      qrCodeData,
      loading,
      error,
      useMockData,
      authUrl,
      authLoading,
      handleGetAuthUrl,
      handleEnvironmentChange,
      isBrowser,
      isAlipayAuthCallback,
      alipayAuthCode,
      alipayBuyerId,
      wechatAuthCode,
      wechatBuyerId,
    };
  },
});
</script>

<style scoped>
.beefgate-container {
  padding: 20px;
  font-family: Arial, sans-serif;
  max-width: 600px;
  margin: 0 auto;
  text-align: center;
}

.loading,
.error {
  margin-top: 15px;
  padding: 10px;
  border-radius: 4px;
}

.loading {
  color: #31708f;
  background-color: #d9edf7;
  border: 1px solid #bce8f1;
}

.error {
  color: #a94442;
  background-color: #f2dede;
  border: 1px solid #ebccd1;
}

.qr-data {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #ccc;
  border-radius: 4px;
  text-align: left;
  background-color: #f9f9f9;
}

.qr-data pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  background-color: #fff;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin: 0;
}

:deep(.ant-collapse) {
  background: transparent;
  border: none;
}

:deep(.ant-collapse-item) {
  border: none;
}

:deep(.ant-collapse-header) {
  color: #1890ff !important;
  font-weight: 500;
}

:deep(.ant-collapse-content) {
  border: none;
  background: transparent;
}
</style>